<?php
// filepath: /path/to/refresh_token.php

// 配置日志记录
$log_file = __DIR__ . '/logs/app.log';
if (!file_exists(__DIR__ . '/logs')) {
    mkdir(__DIR__ . '/logs', 0777, true);
}

function log_message($level, $message)
{
    global $log_file;
    $date = date('Y-m-d H:i:s');
    $log_entry = "[$date] $level: $message" . PHP_EOL;
    file_put_contents($log_file, $log_entry, FILE_APPEND);
}

// 固定的client_id和client_secret
$client_id = '4628137f49914dc2';
$client_secret = '74e23ce3db7243bc8f853b04';
$token_url = 'https://api.atomgit.com/login/oauth/access_token';

// 检查tokens.json文件是否存在
if (!file_exists("tokens.json")) {
    log_message('INFO', 'tokens.json文件不存在，跳过更新。');
    exit;
}

// 获取需要刷新的令牌
$tokens = getTokens();
if (!isset($tokens['refresh_token'])) {
    log_message('INFO', 'tokens.json中不存在refresh_token，跳过更新。');
    exit;
}

$refresh_token = $tokens['refresh_token'];

// 构建请求数据
$data = array(
    'client_id' => $client_id,
    'client_secret' => $client_secret,
    'grant_type' => 'refresh_token',
    'refresh_token' => $refresh_token
);

// 初始化cURL会话
$ch = curl_init($token_url);

// 设置cURL选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

// 执行cURL请求
$response = curl_exec($ch);

// 检查cURL错误
if (curl_errno($ch)) {
    log_message('ERROR', 'cURL Error: ' . curl_error($ch));
    curl_close($ch);
    exit;
}

// 关闭cURL会话
curl_close($ch);

// 解析响应
$response_data = json_decode($response, true);
$new_access_token = $response_data['access_token'];
$new_refresh_token = $response_data['refresh_token'];

// 更新令牌
updateTokens($new_access_token, $new_refresh_token);

log_message('INFO', 'Access token and refresh token updated successfully.');

function getTokens() {
    // 实现获取令牌的逻辑，例如从数据库中获取
    // 这里仅作示例
    return json_decode(file_get_contents("tokens.json"), true);
}

function updateTokens($access_token, $refresh_token) {
    // 实现更新令牌的逻辑，例如更新到数据库
    // 这里仅作示例
    file_put_contents("tokens.json", json_encode([
        'access_token' => $access_token,
        'refresh_token' => $refresh_token
    ]));
}
?>
